package com.ruoyi.biz.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * todo
 *
 * @author yusheng.liu
 * @since 2025/11/14 14:44
 */
public class SizeParser {

    // 支持 B, KB, MB, GB, TB（大小写不敏感），允许数字前后有空格，单位前可有空格
    private static final Pattern SIZE_PATTERN = Pattern.compile(
            "^\\s*([0-9]+(?:\\.[0-9]+)?)\\s*([KMGT]?B)\\s*$",
            Pattern.CASE_INSENSITIVE
    );

    /**
     * 将如 "1KB", "2.5 GB", "512B" 等字符串转换为字节数。
     *
     * @param sizeStr 带单位的容量字符串，例如 "1MB", "758KB", "3 GB"
     * @return 对应的字节数（以 long 表示）
     * @throws IllegalArgumentException 如果格式无效
     */
    public static long parseSizeToBytes(String sizeStr) {
        if (sizeStr == null || sizeStr.trim().isEmpty()) {
            throw new IllegalArgumentException("Input size string is null or empty");
        }

        Matcher matcher = SIZE_PATTERN.matcher(sizeStr);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("Invalid size format: " + sizeStr);
        }

        double value = Double.parseDouble(matcher.group(1));
        String unit = matcher.group(2).toUpperCase();

        long multiplier;
        switch (unit) {
            case "B":
                multiplier = 1L;
                break;
            case "KB":
                multiplier = 1024L;
                break;
            case "MB":
                multiplier = 1024L * 1024L;
                break;
            case "GB":
                multiplier = 1024L * 1024L * 1024L;
                break;
            case "TB":
                multiplier = 1024L * 1024L * 1024L * 1024L;
                break;
            default:
                throw new IllegalArgumentException("Unsupported unit: " + unit);
        }

        double bytes = value * multiplier;
        if (bytes > Long.MAX_VALUE || bytes < 0) {
            throw new IllegalArgumentException("Size too large to fit in long: " + sizeStr);
        }

        return (long) bytes;
    }

    // 示例测试
    public static void main(String[] args) {
        String[] testCases = {"8GB", "10.8GB", "3GB", "10MB", "20GB", "10GB", " 100 MB "};

        for (String test : testCases) {
            try {
                long bytes = parseSizeToBytes(test);
                System.out.printf("%-10s -> %d bytes%n", test, bytes);
            } catch (Exception e) {
                System.err.println("Error parsing '" + test + "': " + e.getMessage());
            }
        }
    }
}
